package cn.akaba.yun.appCls;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Arrays;
import java.util.Base64;
import java.util.HashMap;
import java.util.ResourceBundle;

public class AppDataBase {
    private static AppDataBase instance;
    public static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
    public static final String TPL_DB_URL = "jdbc:mysql://${ip}:${port}/${database}?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC";
    private Connection mysqlConnection;
    private AppDataBase() {
        this.connectionMysql();
    }

    private void connectionMysql() {
        HashMap<String, Object> infoMap = this.getConnectionInfo();
        String dbURL = AppStringTool.format(AppDataBase.TPL_DB_URL, infoMap);
        try {
            this.mysqlConnection = DriverManager.getConnection(dbURL);
        } catch (SQLException sqlException) {
            sqlException.printStackTrace();
        }
    }

    private HashMap<String, Object> getConnectionInfo() {
        ResourceBundle resourceBundle = ResourceBundle.getBundle("database");
        String encodedPassword = resourceBundle.getString("password");
        String password = AppStringTool.base64Decode(encodedPassword);
        HashMap<String, Object> infoMap = new HashMap<>();
        infoMap.put("password", password);
        String[] keyList = new String[]{
            "ip",
            "port",
            "database",
            "user"
        };
        for (String key : keyList) {
            infoMap.put(key, resourceBundle.getString(key));
        }
        return infoMap;
    }

    public static AppDataBase getInstance() {
        if (AppDataBase.instance == null) {
            AppDataBase.instance = new AppDataBase();
        }
        return AppDataBase.instance;
    }

    public boolean executeSql(String sql) {
        try {
            Statement statement = this.mysqlConnection.createStatement();
            return statement.execute(sql);
        } catch (SQLException sqlException) {
            sqlException.printStackTrace();
            return false;
        }
    }
}
